package com.yxym.ticket;

//实现多线程，模拟三个窗口售票的信息...
public class CellTicket {
    public static void main(String[] args) throws InterruptedException {
        //测试Thread方式
        SellTicket01 sellTicket01 = new SellTicket01();
        SellTicket01 sellTicket02 = new SellTicket01();
        SellTicket01 sellTicket03 = new SellTicket01();
        //Thread thread = new Thread(sellTicket01);
        sellTicket01.start();
//        sellTicket02.start();
//        sellTicket03.start();
        //System.out.println("====================");
        //让sellTicket退出run方法，终止线程
        Thread.sleep(10 * 100);
        sellTicket01.setLoop(false);

//        //测试Runnable方式
//        SellTicket02 sellTicket04 = new SellTicket02();
//        Thread thread = new Thread(sellTicket04);
//        thread.start();
    }
}

//使用Thread方式
class SellTicket01 extends Thread{
    private static int ticketNums = 100;//多个线程共享
    private boolean loop = true;

    public void setLoop(boolean loop) {
        this.loop = loop;
    }

    @Override
    public void run() {
        while(loop){
            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            if (ticketNums <= 0){
                System.out.println("售票结束...");
                break;
            }
            System.out.println("窗口"
                    + Thread.currentThread().getName()+
                    "售出一张票" + "剩余的票数=" + (ticketNums--));
        }
    }
}

class SellTicket02 implements Runnable{
    private int ticketNums = 100;//多线程共享ticketNums

    @Override
    public void run() {
        while (true){
            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            if(ticketNums <= 0){
                System.out.println("售票结束...");
                break;
            }
            System.out.println("窗口"
                    + Thread.currentThread().getName()+
                    "售出一张票" + "剩余的票数=" + (ticketNums--));
        }
    }
}